#include <Arduino.h>
#include <Wire.h>

// 前向声明（必须与函数定义完全一致）
void scanForPCA9685();  // 修改此处：原代码可能声明为 scanI2CDevices()
void checkCommonIssues();

// I2C 配置
#define I2C_SDA 21
#define I2C_SCL 22
#define I2C_FREQ 100000

// PCA9685地址配置
const uint8_t PCA9685_ADDRESSES[] = {0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F};
const int PCA9685_COUNT = 2;

void setup() {
  Serial.begin(115200);
  Wire.begin(I2C_SDA, I2C_SCL, I2C_FREQ);
  delay(2000);
  Serial.println("\nStarting I2C Scanner for PCA9685...");
}

void loop() {
  scanForPCA9685();  // 确保调用名称与前向声明一致
  delay(5000);
}

// 函数实现（名称必须与前向声明一致）
void scanForPCA9685() {
  uint8_t foundAddresses[PCA9685_COUNT] = {0};
  int foundCount = 0;

  Serial.println("Scanning for PCA9685 devices...");
  
  for (size_t i = 0; i < sizeof(PCA9685_ADDRESSES)/sizeof(PCA9685_ADDRESSES[0]); i++) {
    uint8_t address = PCA9685_ADDRESSES[i];
    Wire.beginTransmission(address);
    uint8_t error = Wire.endTransmission();

    if (error == 0) {
      Serial.printf("Found PCA9685 at 0x%02X", address);
      
      if (foundCount < PCA9685_COUNT) {
        foundAddresses[foundCount] = address;
        foundCount++;
      }

      if (address == 0x40) {
        Serial.println(" (Default address)");
      } else {
        Serial.print(" (Address pins: ");
        uint8_t offset = address - 0x40;
        for (int pin = 0; pin < 5; pin++) {
          if (offset & (1 << pin)) {
            Serial.print("A"); Serial.print(pin); Serial.print("=HIGH ");
          }
        }
        Serial.println(")");
      }
    }
  }

  if (foundCount >= PCA9685_COUNT) {
    Serial.println("\nSuccessfully found all PCA9685 devices:");
    for (int i = 0; i < foundCount; i++) {
      Serial.printf("PCA9685 #%d: 0x%02X\n", i+1, foundAddresses[i]);
    }
  } else if (foundCount > 0) {
    Serial.printf("\nFound only %d PCA9685 (expected %d)\n", foundCount, PCA9685_COUNT);
    checkCommonIssues();  // 确保调用名称一致
  } else {
    Serial.println("\nNo PCA9685 devices found!");
    checkCommonIssues();  // 确保调用名称一致
  }
}

// 函数实现（名称必须与前向声明一致）
void checkCommonIssues() {
  Serial.println("\nTroubleshooting Tips:");
  Serial.println("1. Check I2C connections (SDA/SCL)");
  Serial.println("2. Verify power supply (5V)");
  Serial.println("3. Confirm address pins configuration");
  Serial.println("4. Ensure pull-up resistors (4.7kΩ)");
}